﻿(function(window) {
    window.jDoc = window.jDoc || function(id) {
        if (typeof id == "string") {
            if (id.startWith("#")) {
                id = id.substring(1, id.length)
            }
            return document.getElementById(id);
        }
        return id;
    };
    jDoc.site = {};
    var _hostName = ".enntrading.com";
    if (window.location.host.indexOf("900ku.com") >= 0) {
        _hostName = ".900ku.com";
    }
    jDoc.site.getHost = function() {
        return _hostName;
    }
    jDoc.site.setHost = function(hostName) {
        _hostName = hostName;
        setSiteLink();
    }
    function setSiteLink() {
        var siteName = ["test", "buy", "trade", "passport", "bidding", "www", "js", "css", "search", "help", "dl", "main"];
        for (var i = 0, len = siteName.length; i < len; i++) {
                jDoc.site[siteName[i]] = "http://" + siteName[i] + _hostName;
        }
    }
    setSiteLink();
    jDoc.menu = {};
    jDoc.menu.ajaxResult = {};
    jDoc.menu.init = function() {
        jDoc.getElementsBy("nav", "a", function(elem) {
            var siteName = elem.getAttribute("site-name");
            if (siteName) {
                var host = jDoc.site[siteName];
                var currHost = window.location.host;
                elem.href = host + elem.getAttribute("site-url");
                if (("http://" + currHost) == jDoc.site.trade || ("http://" + currHost) == jDoc.site.bidding) {
                    return;
                }
                elem.parentNode.className = "";
                if (("http://" + window.location.host) == jDoc.site.search) {
                    if (window.location.href.toLowerCase().indexOf(elem.href.toLowerCase()) == 0) {
                        elem.parentNode.className = "this";
                    }
                }
            }
            if (jDoc("aHome"))
                jDoc("aHome").href = jDoc.site.www;
        });

        jDoc("_FooterEmail").src = jDoc.site.css + "/PubImg/pic_email.gif";
        jDoc("_FooterGongshang").src = jDoc.site.css + "/PubImg/gongshang_logos.gif";

        var keyWordDefault = "请填写搜索关键词"
        $("#_txtKeyWords").val(keyWordDefault);
        $("input[name=_SearchType][value=1]").attr("checked", "1");

        //选择产品
        $("#_radioProduct").click(function() {
            $("input[name=_SearchType][value=1]").attr("checked", "1");
        });
        //选择公司
        $("#_radioCorp").click(function() {
            $("input[name=_SearchType][value=2]").attr("checked", "1");
        });
        //选择求购
        $("#_radioBuy").click(function() {
            $("input[name=_SearchType][value=3]").attr("checked", "1");
        });

        $("#_txtKeyWords").focusin(function() {
            //获得焦点事件
            if ($.trim($(this).val()) == keyWordDefault) {
                $(this).val("");
            }
        }).focusout(function() {
            //失去焦点事件
            if ($.trim($(this).val()) == "") {
                $(this).val(keyWordDefault);
            }
        });

        //设置搜索触发的时间
        $("#_BtnSearch").click(function() {
            var searchType = $('[name="_SearchType"][checked=true]:radio').val();
            var keyword = $.trim($("#_txtKeyWords").val());
            if (keyword != keyWordDefault) {
                switch (parseInt(searchType)) {
                    case 1:
                        window.open(jDoc.site.search + '/PResult.aspx?t=' + searchType + "&kw=" + encodeURIComponent(keyword), '_blank');
                        break;
                    case 2:
                        window.open(jDoc.site.search + '/CResult.aspx?t=' + searchType + "&kw=" + encodeURIComponent(keyword), '_blank');
                        break;
                    case 3:
                        window.open(jDoc.site.search + '/Bid/BidSearch.aspx?t=' + searchType + "&kw=" + encodeURIComponent(keyword), '_blank');
                        break;
                    default:
                        break;
                }
            }
            else {
                alert(keyWordDefault);
            }
        });

        $(document.body).bind("keypress", function() {
            var keyCode = jDoc.getEvent().keyCode;
            if (keyCode == 13) {
                var event = jDoc.getEvent();
                var srcID = event.srcElement ? event.srcElement.id : event.target.id;
                if (srcID == "_txtKeyWords") {
                    $(jDoc("_BtnSearch")).click();
                }
            }
        });
        window.userInfo = null;
        if (jDoc("loginedInfo"))
            $.getScript(jDoc.site.passport + '/Ajax/LoginForJS.ashx?t=1&ran=' + Math.random(),
                function() {
                    if (userInfo != null && userInfo != undefined && userInfo.success) {
                        jDoc("loginedInfo").style.display = "";
                        jDoc("loginedAlert").style.display = "";
                        jDoc("aLoginOut").href = jDoc.site.passport + '/Loginout.aspx';
                        jDoc("imgSound").src = jDoc.site.css + "/PubImg/laba.jpg";
                        jDoc("spUserName").innerHTML = userInfo.loginName;
                        jDoc("spNotReadMessage").innerHTML = userInfo.noReadMsgNum;
                        var notDoNum = 0
                        switch (userInfo.businessType) {
                            case 0: //采购
                                notDoNum = parseInt(userInfo.orderInfo.buyerOrderNum) + parseInt(userInfo.orderInfo.buyerRateNum);
                                if (userInfo.right.IsAdministrator) { //如果是管理员则出现审批功能导向
                                    notDoNum = notDoNum + parseInt(userInfo.orderInfo.approvalNum);
                                }
                                break;
                            case 1: //销售
                                notDoNum = parseInt(userInfo.offlineProductNum) + parseInt(userInfo.orderInfo.supplierOrderNum) + parseInt(userInfo.orderInfo.supplierRateNum);
                                break;
                            default:
                                break;
                        }
                        jDoc("spNotDoNum").innerHTML = notDoNum;
                    }
                    else {
                        jDoc("beforLogin").style.display = "";
                        jDoc("aLogin").href = jDoc.site.passport + '/Login.aspx';
                        jDoc("aRegedit").href = jDoc.site.passport + '/MemberRegedit.aspx';
                    }
                }
            );
    }

    Object.extend(
    window.jDoc
    , {
        getElementsBy: function(rangeID, tagName, applyFn) {
            var rangeEle = jDoc(rangeID);
            if (!rangeEle) { rangeEle = document.body || document.documentElement }
            var resultList = [];
            if (tagName) {
                var tagNameList = [];
                if (tagName.join === undefined) {
                    tagNameList.push(tagName);
                } else {
                    tagNameList = tagName;
                }
                for (var i = 0, len = tagNameList.length; i < len; i++) {
                    var eleList = rangeEle.getElementsByTagName(tagNameList[i]);
                    var fn = (typeof applyFn == "function") ? applyFn : function(param) { return true; };
                    for (var k = 0, kLen = eleList.length; k < kLen; k++) {
                        var result = fn(eleList[k]);
                        if (result == "-1") {
                            break;
                        } else if (result) {
                            resultList.push(eleList[k]);
                        }
                    }
                }
            } else {
                alert("tagName is not null")
            }
            return resultList;
        }
        , formatEvent: function(oEvent) {
            if ($.browser.msie) {
                oEvent.charCode = (oEvent.type == "keypress") ? oEvent.keyCode : 0;
                oEvent.eventPhase = 2;
                oEvent.isChar = (oEvent.charCode > 0);
                oEvent.pageX = oEvent.clientX + document.body.scrollLeft;
                oEvent.pageY = oEvent.clientY + document.body.scrollTop;
                oEvent.preventDefault = function() {
                    this.returnValue = false;
                };

                if (oEvent.type == "mouseout") {
                    oEvent.relatedTarget = oEvent.toElement;
                } else if (oEvent.type == "mouseover") {
                    oEvent.relatedTarget = oEvent.fromElement;
                }

                oEvent.stopPropagation = function() {
                    this.cancelBubble = true;
                };

                oEvent.target = oEvent.srcElement;
                oEvent.time = (new Date).getTime();
            }
            return oEvent;
        }
        , getEvent: function() {
            if (window.event) {
                return this.formatEvent(window.event);
            } else {
                var o = jDoc.getEvent.caller;
                while (o) {
                    if (typeof o.arguments[0]["charCode"] == "number") {
                        return o.arguments[0];
                    } else {
                        o = o.caller;
                    }
                }
                //return jDoc.getEvent.caller.arguments[0];
            }
        }
        , addEventHandler: function(oTarget, sEventType, fnHandler) {
            if (oTarget.addEventListener) {
                oTarget.addEventListener(sEventType, fnHandler, false);
            } else if (oTarget.attachEvent) {
                oTarget.attachEvent("on" + sEventType, fnHandler);
            } else {
                oTarget["on" + sEventType] = fnHandler;
            }
        }
        , removeEventHandler: function(oTarget, sEventType, fnHandler) {
            if (oTarget.removeEventListener) {
                oTarget.removeEventListener(sEventType, fnHandler, false);
            } else if (oTarget.detachEvent) {
                oTarget.detachEvent("on" + sEventType, fnHandler);
            } else {
                oTarget["on" + sEventType] = null;
            }
        }
        , parseJSONText: function(text) {
            return (new Function("return " + text))();
        }
        , createHtml: function(oHtmlAttr) {
            var html = [];
            html.push("<input ");

            for (var e in oHtmlAttr) {
                html.push(" " + e + "='" + oHtmlAttr[e] + "'");
            }

            html.push("></input>");

            return html.join("");
        },
        reload: function(hashValue) {
            if (hashValue != undefined) {
                var url = [];
                url.push(window.location.href.replace(/(_hv_)[^&]*/, ""));
                if (url[0].indexOf("?") > 0) {
                    if (url[0].endWith("&") == false) {
                        url.push("&");
                    }
                } else {
                    url.push("?")
                }
                url.push("_hv_=" + hashValue);
                window.location.replace(url.join(""));
            }
            else {
                window.location.replace(window.location);
            }
        },
        setHashByUrl: function() {
            var hv = jDoc.queryStringByUrl("_hv_");
            if (hv != null && hv.trim() != "") {
                if (jDoc("a_" + hv)) {
                    jDoc("a_" + hv).scrollIntoView(true);
                } else {
                    window.location.hash = "";
                    window.location.hash = hv;
                }
            }
        },
        delayLoadingImage: function(range) {
            function delayFn() {
                var win = $(window), winScrollTop = win.height() + win.scrollTop(), imgTop;
                jDoc.getElementsBy(range
                    , "img"
                    , function(elem) {
                        if (elem.getAttribute("value")) {
                            imgTop = $(elem).offset().top;
                            if (imgTop <= winScrollTop) {
                                elem.src = elem.getAttribute("value");
                                elem.setAttribute("value", "");
                            }
                        }
                    })
            }
            jDoc.addEventHandler(window, "scroll", delayFn);
            delayFn();
        },
        queryStringByUrl: function(paramName, url) {
            url = url ? url : window.location.search;
            var reg = new RegExp("(^|&)" + paramName.toLowerCase() + "=([^&]*)(&|$)");
            var r = "";
            if (url.indexOf("?") == 0) {
                r = url.toLowerCase().substr(1).match(reg);
            } else {
                r = url.toLowerCase().match(reg);
            }
            if (r != null) {
                return (r[2]); //unescape
            }
            return null;
        },
        addBookmark: function(title, url) {
            title = title == undefined ? document.title : title;
            url = url == undefined ? document.location : url;
            if (window.sidebar) {
                window.sidebar.addPanel(title, url, "");
            } else if (document.all) {
                window.external.AddFavorite(url, title);
            } else if (window.opera && window.print) {
                return true;
            }
        }
    }
    , false);
})(window);
var CheckBox = {
    selected: function(selectRange, checked, excludeName) {
        var eles = selectRange.getElementsByTagName("input");
        for (var i = 0, len = eles.length; i < len; i++) {
            if (eles[i].type == "checkbox" && eles[i].name != excludeName) {
                eles[i].checked = checked;
            }
        }
    },
    selectedByNamePre: function(selectRange, namePre, checked) {
        this.selectedByProperty(selectRange, namePre, checked, "name");
    },
    selectedByIDPre: function(selectRange, idPre, checked) {
        this.selectedByProperty(selectRange, idPre, checked, "id");
    },
    selectedByProperty: function(selectRange, propertyValuePre, checked, propertyName) {
        var eles = selectRange.getElementsByTagName("input");
        for (var i = 0, len = eles.length; i < len; i++) {
            if (eles[i].type == "checkbox" && eles[i][propertyName].toLowerCase().indexOf(propertyValuePre.toLowerCase()) >= 0) {
                eles[i].checked = checked;
            }
        }
    },
    check: function(selectRange, showMessage, failMessage) {
        if (selectRange) {
            var eles = selectRange.getElementsByTagName("input");
            for (var i = 0, len = eles.length; i < len; i++) {
                if (eles[i].type == "checkbox" && eles[i].name != 'allbox') {
                    if (eles[i].checked) {
                        if (showMessage != "") {
                            return confirm(showMessage);
                        } else {
                            return true;
                        }
                    }
                }
            }
        }
        if (failMessage != undefined && failMessage.trim() != "") {
            alert(failMessage);
        }
        return false;
    },
    isAll: function(selectRange, allBoxIDList, idPre) {
        var eles = selectRange.getElementsByTagName("input");
        var flag = true;
        for (var i = 0, len = eles.length; i < len; i++) {
            if (eles[i].type == "checkbox") {
                if (idPre != undefined) {
                    if (eles[i].id.indexOf(idPre) >= 0 && eles[i].checked == false && allBoxIDList.contains(eles[i].id) == false) {
                        flag = false; break;
                    }
                } else {
                    if (eles[i].checked == false && allBoxIDList.contains(eles[i].id) == false) {
                        flag = false; break;
                    }
                }
            }
        }
        for (var i = 0, len = allBoxIDList.length; i < len; i++) {
            var temp = jDoc(allBoxIDList[i]);
            if (temp) {
                temp.checked = flag;
            }
        }
    }
};
function oPopupArea(defaultValue, callbackFn) {
    this.defaultValue = (typeof defaultValue != undefined && defaultValue != null) ? defaultValue : "";
    this.callbackFn = (typeof callbackFn == "function" && callbackFn != null) ? callbackFn : null;
}
oPopupArea.prototype = {
    resetValue: function(ids) {
        this.defaultValue = (typeof ids != undefined && ids != null) ? ids : "";
        this.bindDropDownList.apply(this, this.idList);
    },
    bindDropDownList: function() {
        this.idList = [];
        var callbackFn = this.callbackFn;
        for (var i = 0, iLen = arguments.length; i < iLen; i++) {
            this.idList.push(arguments[i]);
            if (arguments[i + 1]) {
                var ele = arguments[i + 1];
                var ids = [];
                for (var m = i + 1, mLen = arguments.length; m < mLen; m++) {
                    ids.push(arguments[m]);
                }
                var data = { nextChild: ele, clearIDs: ids };
                var ele = $("#" + arguments[i]);
                ele.attr("index", i + 1);
                ele.unbind("change");
                ele.bind("change", data, function(data) {
                    var pid = this.options[this.selectedIndex].value;
                    for (var n = 0, dLen = data.data.clearIDs.length; n < dLen; n++) {
                        oPopupArea.removeDataForDropDownList(data.data.clearIDs[n]);
                    }
                    oPopupArea.bindDataToDropDownList(data.data.nextChild, pid);
                    if (callbackFn) {
                        callbackFn(this.getAttribute("index"), this.options[this.selectedIndex].text, pid);
                    }
                });
            }
        }
        var lastEle = $("#" + arguments[arguments.length - 1]);
        lastEle.attr("index", arguments.length);
        lastEle.unbind("change");
        lastEle.bind("change", function() {
            if (callbackFn) {
                callbackFn(this.getAttribute("index"), this.options[this.selectedIndex].text, this.options[this.selectedIndex].value);
            }
        });
        if (arguments.length > 0) {
            var idList = this.defaultValue.split(",");
            oPopupArea.bindDataToDropDownList(arguments[0], 0, idList[0]);
            if (idList.length > 1) {
                for (var i = 1, iLen = idList.length; i < iLen; i++) {
                    if (arguments[i])
                        oPopupArea.bindDataToDropDownList(arguments[i], idList[i - 1], idList[i]);
                }
            }
        }
    }
}
oPopupArea.url = "/ShareCode/GetCode.ashx?";
oPopupArea.list = [];
oPopupArea.bindDataToDropDownList = function(eleId, pid, defaultValue, callback) {
    var sel = jDoc(eleId);
    $.getJSON(oPopupArea.url,
            { cid: "2", pid: pid },
            function(jsonData) {
                sel.options[0] = new Option("请选择", "-1");
                for (var i = 1, dLen = jsonData.length; i <= dLen; i++) {
                    var obj = jsonData[i - 1];
                    sel.options[i] = new Option(obj["CodeNameCN"], obj["CodeID"]);
                }
                if (typeof defaultValue != "undefined" && defaultValue != "" && defaultValue != null) {
                    sel.value = defaultValue;
                }
                if (callback) {
                    callback();
                }
            }
        );
}
oPopupArea.removeDataForDropDownList = function(eleId) {
    var sel = jDoc(eleId);
    for (var i = sel.length - 1; i >= 1; i--) {
        sel.removeChild(sel.options[i]);
    }
}
// 取当前页面名称(不带后缀名)
function pageName() {
    var a = location.href;
    var b = a.split("/");
    var c = b.slice(b.length - 1, b.length).toString(String).split(".");
    return c.slice(0, 1);
}
// 取当前页面名称(不带后缀名)
function pageUrl() {
    var a = location.href;
    var b = a.split("?");
    return b[0];
}